package com.bite.blog.controller;

import com.bite.blog.model.BlogInfo;
import com.bite.blog.model.Result;
import com.bite.blog.service.BlogService;
import com.bite.blog.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    private BlogService blogService;

    //获取博客列表
    @RequestMapping("/getlist")
    public List<BlogInfo> getBlogList() {
        return blogService.getBlogList();
    }

    //获取博客详情
    @RequestMapping("/getBlogDetail")
    public BlogInfo getBlogDeatail(Integer blogId,HttpServletRequest request){
        BlogInfo blog = blogService.getBlogDeatil(blogId);

//获取当前登录用户ID
        String jwtToken = request.getHeader("user_token");
        Integer loginUserId = JwtUtils.getUserIdFromToken(jwtToken);
        if (loginUserId!=null && blog.getUserId()==loginUserId){
            blog.setLoginUser(1);
        }
        return blog;
    }

    @RequestMapping("/add")
    public Result insert(String title, String content, HttpServletRequest request){
//获取当前登录用户ID
        String jwtToken = request.getHeader("user_token");
        Integer loginUserId = JwtUtils.getUserIdFromToken(jwtToken);
        if (loginUserId==null || loginUserId<1){
            return Result.fail("用户未登录");
        }
        BlogInfo blog = new BlogInfo();
        blog.setUserId(loginUserId);
        blog.setTitle(title);
        blog.setContent(content);
        blogService.insertBlog(blog);
        return Result.success(true);
    }

    @RequestMapping("/update")
    public Result update(@RequestBody BlogInfo blog){
        blogService.updateBlog(blog);
        return Result.success(true);
    }

    @RequestMapping("/delete")
    public boolean delete(Integer blogId){
        blogService.deleteBlog(blogId);
        return true;
    }
}
